package com.zhuhjay.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.ruiji.domain.Dish;
import com.zhuhjay.ruiji.domain.DishFlavor;
import com.zhuhjay.ruiji.domain.dto.DishDto;
import com.zhuhjay.ruiji.mapper.DishMapper;
import com.zhuhjay.ruiji.service.ICategoryService;
import com.zhuhjay.ruiji.service.IDishFlavorService;
import com.zhuhjay.ruiji.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author ZhuHJay
 * @since 2022-05-15
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private ICategoryService categoryService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDishAndFlavor(DishDto dishDto) {
        // 保存菜品基本信息
        save(dishDto);

        Long dishId = dishDto.getId();
        dishDto.getFlavors().forEach(dishFlavor -> dishFlavor.setDishId(dishId));

        // 保存口味信息
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    @Override
    public DishDto queryDishAndFlavor(Long id) {
        // 查询菜品口味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        // 查询菜品信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish, dishDto);

        dishDto.setFlavors(dishFlavors);
        // 修改菜品分类
        dishDto.setCategoryName(categoryService.getById(dish.getCategoryId()).getName());
        return dishDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDishAndFlavor(DishDto dishDto) {
        // 修改菜品基本信息
        updateById(dishDto);

        // 删除当前菜品所有的口味信息
        dishFlavorService.remove(new LambdaQueryWrapper<DishFlavor>()
                .eq(DishFlavor::getDishId, dishDto.getId()));

        // 重新添加所有的口味信息
        dishDto.getFlavors().forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));

        // 保存口味信息
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }
}
